/* eslint-disable default-case */
import { message } from 'antd';
import router from 'umi/router';
import {
  suppBusiScope,
  getSuppList,
  getPdList,
  getAreaPlcyParam,
  getAreaList,
  getInsLsPkgName,
  getAccuLsPkgName,
  getDetail,
  getUpdate,
  getAdd,
  deleteBusiness,
  getDownloadInfoScope,
  uploadFileScope,
  // getPlatformPdList, // 平台管理员获取产品接口
  fetchPlatFormPdList,
  getMgrSuppList,
  getMgrSuppListByUser
} from '@/services/supplymanage';
import _ from 'lodash';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'businessscope';

export default {
  namespace,
  state: {
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    formFieldsValue: {},
    // zj
    supplyNameList: [],
    productList: [],
    suppList: [
      {
        id: 0,
        areaId: '', // 地区
        prodList: '', // 产品
        insAddDeadline: '', // 社保增员截止日期
        insDelDeadline: '', // 社保减员截止日期
        insLsPkgIdList: '', // 社保组合
        accuAddDeadline: '', // 公积金增员截止日期
        accuDelDeadline: '', // 公积金减员截止日期
        accuLsPkgIdList: '', // 公积金组合

        pensAddDeadline: '', // 养老增员截止日
        pensDelDeadline: '', // 养老减员截止日

        unempAddDeadline: '', // 失业增员截止日
        unempDelDeadline: '', // 失业减员截止日

        injAddDeadline: '', // 工伤增员截止日
        injDelDeadline: '', // 工伤减员截止日

        birthAddDeadline: '', // 生育增员截止日
        birthDelDeadline: '', // 生育减员截止日
        medAddDeadline: '', // 医疗增员截止日
        medDelDeadline: '', // 医疗减员截止日
        insUnifyFlag: undefined,
        accuShow: false,
        insShow: false,
        // 社保组合
        insGroupList: [],
        accGroupList: [],
        allProductList: [],
      },
    ],
    areaList: [],
    index: 0,
    resultInfo: {
      // 结果数据必传
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    valuesArr: ['suppCode', 'suppId'],
  },
  effects: {
    // 获取业务范围查看列表
    *getPageList({ payload }, { call, put }) {
      const response = yield call(suppBusiScope, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getPageLookList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // zj
    *fetchSuppList({ payload }, { call, put }) {
      const response = yield call(getSuppList, payload);
      if (response.success) {
        yield put({
          type: 'getSuppList',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *fetchPdList({ payload }, { call, put, select }) {
      const { userType = 1 } = yield select(state => state.login.baseUser);
      // 产品
      const response = yield call(
        // Number(userType) === 1 ? getPlatformPdList : getPdList,
        Number(userType) === 1 ? fetchPlatFormPdList : getPdList,
        Number(userType) === 1 ? {} : payload
      );
      if (response.success && response.data && response.data.length) {
        const newData = response.data.filter(item => item.exetState !== 2);
        yield put({
          type: 'getPdList',
          payload: newData,
        });
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *fetchAreaPlcyParam({ payload }, { call, put }) {
      const response = yield call(getAreaPlcyParam, { areaId: payload.value });
      // 更新地区
      yield put({
        type: 'getAreaValue',
        payload,
      });
      if (response.success) {
        yield put({
          type: 'getAreaPlcyParam',
          payload: { insUnifyFlag: response.data.insUnifyFlag, id: payload.id },
        });
        if (!response.data.insUnifyFlag) {
          message.warning('该地区未配置是否五险合一，请联系管理员！');
        }
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *fetchAreaList({ payload }, { call, put }) {
      const response = yield call(getAreaList, payload);
      if (response.success) {
        yield put({
          type: 'getAreaList',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *getMgrSuppList({ payload }, { call, put }) {
      const res = yield call(getMgrSuppList, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: { supplyNameList: res.data },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *getMgrSuppListByUser({ payload }, { call, put }) {
      const res = yield call(getMgrSuppListByUser, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: { supplyNameList: res.data },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    *fetchInsLsPkgName({ payload }, { call, put, select }) {
      yield put({
        type: 'getInsLsPkgName',
        payload: { id: payload.id, insGroupList: [] },
      });
      yield put({
        type: 'getAreaId',
        payload,
      });

      const selectAreaId = yield select(state => state.businessscope.selectAreaId);
      if (selectAreaId) {
        const response = yield call(getInsLsPkgName, { areaId: selectAreaId });
        if (response.success) {
          yield put({
            type: 'getInsLsPkgName',
            payload: { id: payload.id, insGroupList: response.data },
          });
        } else {
          message.warning(`${response.message || '暂无数据！'}`);
        }
      } else {
        message.warning('请先选择地区！');
      }
    },
    *fetchAccuLsPkgName({ payload }, { call, put, select }) {
      yield put({
        type: 'getAccuLsPkgName',
        payload: { id: payload.id, accGroupList: [] },
      });
      yield put({
        type: 'getAreaId',
        payload,
      });
      const selectAreaId = yield select(state => state.businessscope.selectAreaId);
      if (selectAreaId) {
        const response = yield call(getAccuLsPkgName, { areaId: selectAreaId });
        if (response.success) {
          yield put({
            type: 'getAccuLsPkgName',
            payload: { id: payload.id, accGroupList: response.data },
          });
        } else {
          message.warning(`${response.message || '暂无数据！'}`);
        }
      } else {
        message.warning('请先选择地区！');
      }
    },
    *fetchDetail({ payload }, { call, put, select }) {
      const corpId = yield select(state => state.businessscope.corpId);
      yield put({
        type: 'fetchPdList',
        payload: { corpId },
      });
      // 详情
      const response = yield call(getDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *fetchSave({ payload }, { call, select }) {
      const suppId = yield select(state => state.businessscope.suppId);
      const response = suppId
        ? yield call(getUpdate, { suppId, suppBusiScopeList: payload.suppBusiScopeList })
        : yield call(getAdd, payload);
      if (response.success) {
        message.success(suppId ? '修改成功！' : '新增成功！');
        router.goBack();
      } else {
        message.warning(`${response.message || '暂无数据！'}`);
      }
    },
    *fetchInfor({ payload }, { call }) {
      const response = yield call(getDetail, payload);
      return response;
    },
    *deleteBusiness({ payload }, { call }) {
      const response = yield call(deleteBusiness, payload);
      return response;
    },
    // h获取下载模板信息
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfoScope, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 上传文件:批量进度
    *uploadFileWithProgress({ payload }, { call, put }) {
      try {
        const response = yield call(uploadFileScope, payload);
        if (response.success) {
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.businessscope);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        // 下载错误数据：地址
        resultInfo.errorUrl = '/mgrApi/suppBusiScope/exportErrorExcel';
        // 下载错误数据：参数
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },
  reducers: {
    // 获取业务范围查看列表
    getPageLookList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // zj
    // 获取供应商列表
    getSuppList(state, { payload }) {
      return {
        ...state,
        supplyNameList: Array.isArray(payload) ? payload : [],
      };
    },
    // 获取产品
    getPdList(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        const newItem = item;
        newItem.allProductList = Array.isArray(payload) ? payload : [];
      });
      return {
        ...state,
        ...tempState,
        productList: Array.isArray(payload) ? payload : [],
      };
    },
    // 增加表格
    getAddFrom(state) {
      const tempState = _.cloneDeep(state);
      tempState.index += 1;
      tempState.suppList.push({
        id: tempState.index,
        areaId: '',
        prodList: '',
        insAddDeadline: '',
        insDelDeadline: '',
        insLsPkgIdList: '',
        accuAddDeadline: '',
        accuDelDeadline: '',
        accuLsPkgIdList: '',

        pensAddDeadline: '', // 养老增员截止日
        pensDelDeadline: '', // 养老减员截止日

        unempAddDeadline: '', // 失业增员截止日
        unempDelDeadline: '', // 养老减员截止日
        injAddDeadline: '', // 工伤增员截止日
        injDelDeadline: '', // 工伤减员截止日

        birthAddDeadline: '', // 生育增员截止日
        birthDelDeadline: '', // 生育减员截止日

        medAddDeadline: '', // 医疗增员截止日
        medDelDeadline: '', // 医疗减员截止日

        // from显示
        insUnifyFlag: undefined,
        accuShow: false,
        insShow: false,
        // 社保组合
        insGroupList: [],
        accGroupList: [],
        allProductList: [...tempState.productList],
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 删除表格
    getDelFrom(state, { payload }) {
      const tempState = _.cloneDeep(state);
      const newsuppList = tempState.suppList.filter(
        item => (item.busiScopeId || item.id) !== payload
      );
      return {
        ...state,
        suppList: newsuppList,
      };
    },
    // 改变地区值
    getAreaValue(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem.areaId = payload.value;
        }
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 存储地区id
    getAreaId(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          tempState.selectAreaId = item.areaId;
        }
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 是否五险合一
    getAreaPlcyParam(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem.insUnifyFlag = payload.insUnifyFlag;
        }
      });

      return {
        ...state,
        ...tempState,
      };
    },
    // 页面显示隐藏
    getHas(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem[payload.flag.concat('Show')] = true;
        }
      });

      return {
        ...state,
        ...tempState,
      };
    },
    // 页面显示隐藏
    getHasFalse(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem[payload.flag.concat('Show')] = false;
        }
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 获取地区
    getAreaList(state, { payload }) {
      return {
        ...state,
        areaList: payload,
      };
    },
    // 社保组合
    getInsLsPkgName(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem.insGroupList = payload.insGroupList;
        }
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 公积金组合
    getAccuLsPkgName(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem.accGroupList = payload.accGroupList;
        }
      });
      return {
        ...state,
        ...tempState,
      };
    },
    // 详情
    getDetail(state, { payload }) {
      const newState = state;
      payload.suppBusiScopeList.forEach(item => {
        const newItem = item;
        // 判断是不是五险合一
        if (item.pensAddDeadline) {
          newItem.insUnifyFlag = 2;
        } else {
          newItem.insUnifyFlag = 1;
        }
        // 社保
        if (item.prodIdList) {
          if (item.prodId.indexOf('PDINF_0000000001') !== -1) {
            newItem.insShow = true;
          }
          if (item.prodId.indexOf('PDINF_0000000002') !== -1) {
            newItem.accuShow = true;
          }
        }
        newItem.insGroupList = item.insLsPkgList;
        newItem.accGroupList = item.accuLsPkgList;
        newItem.areaList = [];
        newItem.areaList.push({
          areaId: item.areaInfo.areaId,
          areaName: item.areaInfo.areaName,
        });
        newItem.areaInfo.value = newItem.areaInfo.areaId;
        newItem.areaInfo.label = newItem.areaInfo.areaName;
        newItem.areaInfo.key = newItem.areaInfo.areaId;
        const tempArr = [];
        if (newItem.prodList.length) {
          newItem.prodList.forEach(value => {
            if (newState.productList.some(pdItem => pdItem.pdId === value.pdId)) {
              tempArr.push(value.pdId);
            } else {
              newItem.prodList = item.prodList; // 需要提交数据
              tempArr.push(value.pdName);
            }
          });
          newItem.prodLists = tempArr; // 页面显示id集合
        }
        newItem.allProductList = [...newItem.prodList, ...newState.productList]; // 所有产品
      });
      return {
        ...state,
        ...payload,
        suppList: payload.suppBusiScopeList,
      };
    },
    // 更改地区form变化
    getFormChange(state, { payload }) {
      const tempState = _.cloneDeep(state);
      tempState.suppList.forEach(item => {
        if ((item.busiScopeId || item.id) === payload.id) {
          const newItem = item;
          newItem.insShow = false;
          newItem.accuShow = false;
        }
      });
      return {
        ...state,
        suppIds: payload.suppId,
        ...tempState,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
